import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Logger } from '@nestjs/common';
import { CorsMiddleware } from './common/middleware/cors.middleware';
import { setupSwagger } from './setup-swagger';
import { ConfigService } from '@nestjs/config';
import { isDev } from './common/global/env';
import * as cluster from 'cluster';
import { LoggerService } from './shared/logger/logger.service';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // 应用CORS中间件
  const corsMiddleware = new CorsMiddleware();
  app.use(corsMiddleware.use.bind(corsMiddleware));

  // 获取配置服务
  const configService = app.get(ConfigService);


  const { port, globalPrefix } = configService.get('app', { infer: true })

  // 开发环境添加日志拦截器
  if (isDev) {
    const { LoggingInterceptor } = await import('./common/interceptors/logging.interceptor');
    app.useGlobalInterceptors(new LoggingInterceptor());
  }
  app.setGlobalPrefix(globalPrefix)

  setupSwagger(app, configService)
  await app.listen(port, '0.0.0.0', async () => {
    app.useLogger(app.get(LoggerService))
    const url = await app.getUrl()
    const { pid } = process

    // 安全地获取集群状态
    let isMaster = false;
    try {
      // 尝试检查isPrimary (Node.js 16+)
      isMaster = typeof (cluster as any).isPrimary === 'boolean'
        ? (cluster as any).isPrimary
        : (cluster as any).isMaster; // 回退到isMaster (Node.js < 16)
    } catch (e) {
      // 如果出错，默认为非主进程
      isMaster = false;
    }

    const prefix = isMaster ? 'P' : 'W';

    const logger = new Logger('NestApplication')
    logger.log(`[${prefix + pid}] Server running on ${url}`)


    logger.debug(`Document running on http://127.0.0.1:${port}/api-docs`)

    // 原有 logger 不动
    logger.debug(`Knife4j-UI: http://127.0.0.1:${port}/doc.html`);



  })
}

bootstrap();
